const conn = require('../config/datasql');

/** 登录 */
const login = (req, res) => {
  let sql = `select*from user where username="${req.body.username}" and password="${req.body.password}"`;
  conn(sql, (err, result) => {
    if (err) {
      res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
    } else {
      if (result.length) {
        res.send({ code: 1, msg: '登录成功' });
      } else {
        res.send({ code: 0, msg: '账号或密码错误,请重试!' });
      }
    }
  });
};

/** 新增用户 */
const adddUser = async (req, res) => {
  let sql = `select*from user where username="${req.body.username}" `;
  conn(sql, (err, result) => {
    if (err) {
      res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
    } else {
      if (result.length !== 0) {
        res.send({ code: 0, msg: '此用户已存在,请重新进行添加!' });
      } else {
        let addsql = 'insert into user set ?';
        conn(
          addsql,
          (e, r) => {
            if (e) {
              res.send({ code: 503, msg: '服务器目前异常!请稍后重试!' });
            } else {
              if (r.affectedRows == 1) {
                res.send({ code: 1, msg: '新增成功！' });
              } else {
                res.send({ code: 0, msg: '新增失败,请稍后重试!' });
              }
            }
          },
          req.body
        );
      }
    }
  });
};

module.exports = {
  login,
  adddUser,
};
